package com.lily.aidouzixun.ui;

import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lily.aidouzixun.R;
import com.lily.aidouzixun.adapter.MyListAdapter;
import com.lily.aidouzixun.datacenter.ListPageAble;
import com.lily.aidouzixun.util.L;

import java.sql.Date;

/**
 * orientation Vertial<br>
 * The ContentView(GridView, ListView....) must has weight=1;<br>
 * footerView has weight=1
 *
 */
public class PullToRefreshView extends LinearLayout {
	private static final String TAG = "PullToRefreshView";
	
	// refresh states
	private static final int PULL_TO_REFRESH = 2;
	private static final int RELEASE_TO_REFRESH = 3;
	private static final int REFRESHING = 1;
	private static final int DONE = 0;
	private final static int LOADMORE_FAILURE = 4;
	
	public static interface FootViewMode{
		/**
		 * just show the refresh arrow, dismiss soon;<br>
		 * has tipsTxt, arrowImg, lastUpdateTxt, but no progressBar;
		 */
		final static int ArrowShow = 1;
		/**
		 * with progressBar, dismiss on data loading completed; if failure, could reload when clicked. <br>
		 * has tipsTxt and progressBar, but no arrowImg and lastUpdateTxt.
		 */
		final static int ClickAble = 2;
	}
	int footMode = FootViewMode.ClickAble;
   
	private AdapterView<?> mAdapterView;
	private ScrollView mScrollView;

	private int mHeaderState;
	private View mHeaderView;
	private int mHeaderViewHeight;
	private ImageView mHeaderWccImageView;
	private TextView mHeaderTextView;
	private TextView mHeaderUpdateTextView;
	private ProgressBar mHeaderProgressBar;
	
	private int mFooterState;
	private View mFooterView;
	private int mFooterViewHeight;
	private TextView mFooterTextView;
	private ImageView mFooterWccImageView;
	private TextView mFooterUpdateTextView;
	private ProgressBar mFooterProgressBar;
	/**
	 * layout inflater
	 */
	private LayoutInflater mInflater;
	 
	/**
	 * pull state,pull up or pull down;PULL_UP_STATE or PULL_DOWN_STATE
	 */
	
	/**
	 * 变为向下的箭头,改变箭头方向
	 */
	private RotateAnimation mFlipAnimation;
	/**
	 * 变为逆向的箭头,旋转
	 */
	private RotateAnimation mReverseFlipAnimation;
 

	// 用于保证startY的值在一个完整的touch事件中只被记录一次
	private boolean isRecored;
	
	private int lastPos = 0;
	private int startY;
	private int startX;//注意，只有在垂直滑动距离大于水平滑动距离的时候，才会刷新数据
 
	private int firstItemIndex = 0;
	private int lastItemIndex = 0;
	private int sizeOfPage = 0;
 
	private int pageNum = 0;
 
	private int DATA_SIZE = 0;
	
	private final int THIS_PAGE = 0;
	private final int LAST_PAGE = 1;
	private final int NEXT_PAGE = 2;

	private final int HEAD_HEIGHT = 120;
	private final int FOOT_HEIGHT = 120;

	private int which = THIS_PAGE;

	private int state = DONE;
	private boolean isBack;
 
	private boolean needGetNewData = false;
	private boolean needGetMoreData = true;
	private boolean noMoreData = false;
  
	
	public OnRefreshListener refreshListener;
	public GridView gridView;
  

	private ListPageAble mList;
	private ListAdapter mAdapter;



	public PullToRefreshView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public PullToRefreshView(Context context) {
		super(context);
		init();
	}
  
	/** 
	 * @see FootViewMode
	 * @param mode 
	 */
	public void setFootMode(int mode){
		footMode = mode;
		if (footMode == FootViewMode.ClickAble && mFooterView != null) {
			mFooterView.setOnClickListener(new OnClickListener() {				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (state == LOADMORE_FAILURE ) {   
						state = REFRESHING;
 						changeFooterViewByState();					 					 
						L.v(TAG, "由加载失败状态-->refreshing状态");
					} 
				}
			});
		}
	}
 

	/**
	 * 
	 * @param adapter
	 */
	public void setAdapter(ListAdapter adapter) {
		mAdapter = adapter;
		if(mAdapterView instanceof ListView)
			((ListView)mAdapterView).setAdapter(adapter);
		else if(mAdapterView instanceof GridView)
			((GridView)mAdapterView).setAdapter(adapter);
	}
	
	public ListAdapter getAdapter() {
		return mAdapter;
	}

	/**
	 * 
	 * @param list
	 * @return true update WccListAdapter or false
	 */
	@SuppressWarnings("rawtypes")
	public boolean setData(ListPageAble list) {
		mList = list;
		if (mList != null) {
			setNoMoreData(mList.isNoMoreDatas());
			setDataSize(mList.getSize());
 		}
 
		try {
			if (mList != null) {
				((MyListAdapter) mAdapter).setData(mList.getDatas());
			}else {
				((MyListAdapter) mAdapter).setData(null);
			}
			((MyListAdapter) mAdapter).notifyDataSetChanged();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	@SuppressWarnings("rawtypes")
	public ListPageAble getData() {
		return mList;
	}
	
 
	public void setNeedGetNewData(boolean need) {
		needGetNewData = need;
	}

	public void setNeedGetMoreData(boolean need) {
		needGetMoreData = need;
	}
 

	public void setNoMoreData(boolean val) {
		noMoreData = val;
	}

	/**
	 * will change maxPageNum as well
	 * @param size
	 */
	public void setDataSize(int size) {
		DATA_SIZE = size;	 
	}

	/**
	 * will new default one
	 */
	public void setOnScrollListener() {
		if(mAdapterView != null) {
			if(mAdapterView instanceof AbsListView)  {
				 
			((AbsListView)mAdapterView).setOnScrollListener(new OnScrollListener() {

					@Override
					public void onScrollStateChanged(AbsListView view, int scrollState) {
						// TODO Auto-generated method stub
					}
	
					@Override
					public void onScroll(AbsListView view, int firstVisibleItem,
							int visibleItemCount, int totalItemCount) {
						
						firstItemIndex = firstVisibleItem;
						lastItemIndex = firstVisibleItem + visibleItemCount; 
						if(mList != null)
							mList.setLastVisiblePos(firstItemIndex - 1);
						if (totalItemCount > 0)
							sizeOfPage = totalItemCount;
	
						if (refreshListener != null) {
							refreshListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
						}
					}
				});
			}
		}
	 
	}

	/* todo public static void free(int firstVisibleItem, int visibleItemCount,
			int totalItemCount, List<Object> data) {
		PullRefreshListView.syncFree(firstVisibleItem, visibleItemCount,
				totalItemCount, data);
	}*/

	/**
	 * init head, animation, reverseAnimation   
	 * 
	 * @description
	 */
	private void init() {
		// Load all of the animations we need in code rather than through XML
		mFlipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		mFlipAnimation.setInterpolator(new LinearInterpolator());
		mFlipAnimation.setDuration(250);
		mFlipAnimation.setFillAfter(true);
		mReverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		mReverseFlipAnimation.setInterpolator(new LinearInterpolator());
		mReverseFlipAnimation.setDuration(250);
		mReverseFlipAnimation.setFillAfter(true);

		mInflater = LayoutInflater.from(getContext());
		// header view 在此添加,保证是第一个添加到linearlayout的最上端
		addHeaderView();
		// 不能在此添加 addFooterView();
	}

	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();
		// footer view 在此添加保证添加到linearlayout中的最后
		addFooterView();
		try {
			initContentAdapterView();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void addHeaderView() {
		// header view
		mHeaderView = mInflater.inflate(R.layout.listhead, this, false);

		mHeaderWccImageView = (ImageView) mHeaderView.findViewById(R.id.head_arrowImageView);
		mHeaderTextView = (TextView) mHeaderView.findViewById(R.id.head_tipsTextView);
		mHeaderUpdateTextView = (TextView) mHeaderView.findViewById(R.id.head_lastUpdatedTextView);
		mHeaderProgressBar = (ProgressBar) mHeaderView.findViewById(R.id.head_progressBar);

		mHeaderWccImageView.setMinimumWidth(50);
		mHeaderWccImageView.setMinimumHeight(50);
		// header layout
		
		measureView(mHeaderView);
		mHeaderViewHeight = mHeaderView.getMeasuredHeight();
		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, mHeaderViewHeight);
		// 设置topMargin的值为负的header View高度,即将其隐藏在最上方
		//params.topMargin = -(mHeaderViewHeight);
		
		addView(mHeaderView, params);
		setHeaderTopMargin(-mHeaderViewHeight);
	}

	private void addFooterView() {
		// footer view
		mFooterView = mInflater.inflate(R.layout.listfoot, this, false);
		mFooterWccImageView = (ImageView) mFooterView.findViewById(R.id.foot_arrowImageView);
		mFooterTextView = (TextView) mFooterView.findViewById(R.id.foot_tipsTextView);
		mFooterUpdateTextView = (TextView) mFooterView.findViewById(R.id.foot_lastUpdatedTextView);
		mFooterProgressBar = (ProgressBar) mFooterView.findViewById(R.id.foot_progressBar);

		mFooterWccImageView.setMinimumWidth(50);
		mFooterWccImageView.setMinimumHeight(50);
		// footer layout
		measureView(mFooterView);
		mFooterViewHeight = mFooterView.getMeasuredHeight();
		mFooterView.setVisibility(View.GONE);
		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, 0);
		params.weight = 1;
	 	addView(mFooterView, params);
	}
	
	
	/**
	 * init AdapterView like ListView,GridView and so on;or init ScrollView
	 * 
	 */
	private void initContentAdapterView() throws IllegalArgumentException {
		int count = getChildCount();
		if (count < 3) {// 3表示header,footer以及ListView/GridView/ScrollView
			throw new IllegalArgumentException(
					"this layout must contain 3 child views,and AdapterView or ScrollView must in the second position!");
		}
		View view = null;
		for (int i = 0; i < count - 1; ++i) {
			view = getChildAt(i);
			if (view instanceof AdapterView<?>) {
				mAdapterView = (AdapterView<?>) view;
			}
			if (view instanceof ScrollView) {
				// finish later
				mScrollView = (ScrollView) view;
			}
		}
		if (mAdapterView == null && mScrollView == null) {
			throw new IllegalArgumentException(
					"must contain a AdapterView or ScrollView in this layout!");
		}
	}

	private void measureView(View child) {
		ViewGroup.LayoutParams p = child.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
		}

		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
					MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0,
					MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent e) {
		int y = (int)e.getRawY();
		int x = (int)e.getRawX();
		switch (e.getAction()) {
		case MotionEvent.ACTION_DOWN:
			startY = y;
			startX = x;
			break;
		case MotionEvent.ACTION_MOVE:
			// deltaY > 0 是向下运动,< 0是向上运动
			int deltaY = y - startY;
			int deltaX = x - startX;
			if (Math.abs(deltaX) < Math.abs(deltaY) && isRefreshViewScroll(deltaY)) {
				return true;
			}
			break;

		case MotionEvent.ACTION_UP:		
		case MotionEvent.ACTION_CANCEL:
			break;
		}
		return false;
	}

	/*
	 * 如果在onInterceptTouchEvent()方法中没有拦截(即onInterceptTouchEvent()方法中 return false) 
	 * 则由PullToRefreshView 的子View来处理;
	 * 否则由下面的方法来处理(即由PullToRefreshView自己来处理)
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
 		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			L.e(TAG, "onTouchEvent MotionEvent.ACTION_DOWN startY: " + startY);
			if (!isRecored) {
				isRecored = true;
			}
			if (state == LOADMORE_FAILURE) {				
					state = REFRESHING;																
					changeFooterViewByState();
					Log.v(TAG, "LOADMORE_FAILURE状态转变到REFRESHING");
			}
			break;
		case MotionEvent.ACTION_MOVE:
			if (!isRecored) {
				startY = (int) event.getRawY();
				isRecored = true;
			}
			int tempY = (int) event.getRawY();
            int disY = tempY - startY;
        	if (disY > 0) {
				/*if (NEXT_PAGE == which)
					return true;
				else*/
					which = LAST_PAGE;
			} else if (disY < 0) {
				/*if (LAST_PAGE == which)
					return true;
				else*/
					which = NEXT_PAGE;
			}
            
			if (which == LAST_PAGE) {
 				if (firstItemIndex > 0){
					break;}
				if (needGetNewData == false)
					break;
			}
			if (which == NEXT_PAGE) {
				if (lastItemIndex < sizeOfPage - 1)
					break;
				if (needGetMoreData == false || noMoreData == true)
					break;
			}

			if (state != REFRESHING) {
				if (state == DONE){ // init
					if (which == LAST_PAGE) {
						state = PULL_TO_REFRESH;	
						changeHeaderViewByState();
						L.v(TAG, "DONE状态转变到PULL_TO_REFRESH");
					} else if (which == NEXT_PAGE) {
						state = PULL_TO_REFRESH;	
						changeFooterViewByState();
						L.v(TAG, "DONE状态转变到PULL_TO_REFRESH");
					}
				}
				if (state == LOADMORE_FAILURE) {
					if (which == NEXT_PAGE) {
						state = REFRESHING;	
						changeFooterViewByState();
						L.v(TAG, "LOADMORE_FAILURE状态转变到REFRESHING");
					}
				}
				if (state == RELEASE_TO_REFRESH) {
					if (which == LAST_PAGE) {
						// 往上推了，推到了屏幕足够掩盖head的程度，但是还没有推到全部掩盖的地步
						if ((disY < HEAD_HEIGHT) && disY > 0) {
							state = PULL_TO_REFRESH;
							changeHeaderViewByState();
							L.v(TAG, "RELEASE_TO_REFRESH状态转变到PULL_TO_REFRESH状态");
						}
						// 一下子推到顶了
						else if (disY <= 0) {
							state = DONE;
							changeHeaderViewByState();
							L.v(TAG, "RELEASE_TO_REFRESH状态转变到done状态");
						}
						// 往下拉了，或者还没有上推到屏幕顶部掩盖head的地步
						else {
							// 不用进行特别的操作，只用更新paddingTop的值就行了
						 
						}
					} else if (which == NEXT_PAGE) {
						// 往下推了，推到了屏幕足够掩盖foot的程度，但是还没有推到全部掩盖的地步
						if ((-disY < FOOT_HEIGHT) && disY < 0) {
							state = PULL_TO_REFRESH;
							changeFooterViewByState();
							L.v(TAG, "RELEASE_TO_REFRESH状态转变到PULL_TO_REFRESH状态");
						}
						// 一下子推到顶了
						else if (-disY <= 0) {
							state = DONE;
							changeFooterViewByState();
							L.v(TAG, "由RELEASE_TO_REFRESH状态转变到done状态");
						}
						// 往上拉了，或者还没有下推到屏幕底部掩盖foot的地步
						else {
							// 不用进行特别的操作，只用更新paddingTop的值就行了
							 
						}
					}
				}
				// 还没有到达显示松开即可刷新的时候,DONE或者是PULL_To_REFRESH状态
				if (state == PULL_TO_REFRESH) {
					if (which == LAST_PAGE) {
						// 下拉到可以进入RELEASE_TO_REFRESH的状态
						if (disY >= HEAD_HEIGHT) {
							state = RELEASE_TO_REFRESH;
							isBack = true;
							changeHeaderViewByState();
							L.v(TAG, "PULL_TO_REFRESH状态转变到RELEASE_TO_REFRESH");
						}
						// 上推到顶了
						else if (disY <= 0) {
							state = DONE;
							changeHeaderViewByState();
							L.v(TAG, "PULL_TO_REFRESH状态转变到done状态");
						} else {
							 
						}
					} else if (which == NEXT_PAGE) {
						// 上拉到可以进入RELEASE_TO_REFRESH的状态
						if (-disY >= FOOT_HEIGHT && footMode == FootViewMode.ArrowShow) {
							isBack = true;
							state = RELEASE_TO_REFRESH;						 
							 changeFooterViewByState();
							L.v(TAG, "PULL_TO_REFRESH状态转变到RELEASE_TO_REFRESH");
						}
						else if ( -disY >= FOOT_HEIGHT / 3 && footMode == FootViewMode.ClickAble) {  
							state = REFRESHING;							
							changeFooterViewByState();
							L.v(TAG, "PULL_TO_REFRESH状态--->refreshing状态");
						}
						else if (-disY <= 0) {
							state = DONE;
							changeFooterViewByState();
							L.v(TAG, "PULL_TO_REFRESH状态转变到done状态");
						} else {
							 
						}
					}
				}
				
				// 更新head/footView的padding
				if (state == PULL_TO_REFRESH) {
					if (which == LAST_PAGE) {
						setHeaderTopMargin(disY	- mHeaderViewHeight);
					} else if (which == NEXT_PAGE) {
						setFooterBottomHeight( -disY);
					}
				}

				// 更新head/footView的padding
				if (state == RELEASE_TO_REFRESH) {
					if (which == LAST_PAGE) {
						setHeaderTopMargin(disY - mHeaderViewHeight);
					} else if (which == NEXT_PAGE) {
						setFooterBottomHeight( -disY);
					}
				}
			}
	  
			break;
		case MotionEvent.ACTION_UP:
			if (state != REFRESHING) {			 
				if (RELEASE_TO_REFRESH == state) { 
					// 开始刷新
					state = REFRESHING;
					if (which == LAST_PAGE) {
						changeHeaderViewByState();
					 
					} else if (which == NEXT_PAGE) {
						changeFooterViewByState();					 
					}
					L.v(TAG, "由RELEASE_To_REFRESH状态，到refreshing状态");
				}  
				
				if (PULL_TO_REFRESH == state && (which == LAST_PAGE || which == NEXT_PAGE)){
					state = DONE;	
					if (which == LAST_PAGE) {
						changeHeaderViewByState();
					}else if (which == NEXT_PAGE){
						changeFooterViewByState();
					}
					L.v(TAG, "由PULL_To_REFRESH状态，到done状态");
				}				
			}
 
			isRecored = false;
			isBack = false;
			break;
		}
 		return super.onTouchEvent(event);
	}

	// 当状态改变时候，调用该方法，以更新界面
	private void changeHeaderViewByState() {
		switch (state) {
		case RELEASE_TO_REFRESH:
			mHeaderWccImageView.setVisibility(View.VISIBLE);
			mHeaderProgressBar.setVisibility(View.GONE);
			mHeaderTextView.setVisibility(View.VISIBLE);
			mHeaderUpdateTextView.setVisibility(View.VISIBLE);
			mHeaderWccImageView.clearAnimation();
			mHeaderWccImageView.startAnimation(mFlipAnimation);
	 		 
			if (pageNum > 1) 
				mHeaderTextView.setText("松开即可进入上一页");
			else
				mHeaderTextView.setText("松开即可刷新");
			break;
		case PULL_TO_REFRESH:
			mHeaderProgressBar.setVisibility(View.GONE);
			mHeaderTextView.setVisibility(View.VISIBLE);
			mHeaderUpdateTextView.setVisibility(View.VISIBLE);
			mHeaderWccImageView.clearAnimation();
			mHeaderWccImageView.setVisibility(View.VISIBLE);
			// 是由RELEASE_To_REFRESH状态转变来的
			if (isBack) {
				isBack = false;
				mHeaderWccImageView.clearAnimation();
				mHeaderWccImageView.startAnimation(mReverseFlipAnimation);
			}
		 
			if (pageNum > 1) 
				mHeaderTextView.setText("下拉可以进入上一页");
			else
				mHeaderTextView.setText("下拉可以刷新");

			break;
		case REFRESHING:
			setHeaderTopMargin(0);
			mHeaderProgressBar.setVisibility(View.VISIBLE);
			mHeaderTextView.setVisibility(View.VISIBLE);
			mHeaderUpdateTextView.setVisibility(View.VISIBLE);
			mHeaderWccImageView.clearAnimation();
			mHeaderWccImageView.setVisibility(View.GONE); 			
			mHeaderTextView.setText("正在刷新");
			refresh();
			pageNum = 1;
			break;
		case DONE:
			mHeaderProgressBar.setVisibility(View.GONE);
			mHeaderWccImageView.clearAnimation();
			mHeaderWccImageView
					.setImageResource(R.mipmap.black_pull_to_refresh_arrow);
			mHeaderUpdateTextView.setVisibility(View.VISIBLE);
 
			if (pageNum > 1) 
				mHeaderTextView.setText("下拉可以进入上一页");
			else
				mHeaderTextView.setText("下拉可以刷新");
			setHeaderTopMargin(-1 * mHeaderViewHeight);
			break;
		}
	}
	
	// 当状态改变时候，调用该方法，以更新界面
	private void changeFooterViewByState() {
		switch (state) {
		case RELEASE_TO_REFRESH:
			mFooterWccImageView.setVisibility(View.VISIBLE);
			mFooterProgressBar.setVisibility(View.GONE);
			mFooterTextView.setVisibility(View.VISIBLE);
			mFooterUpdateTextView.setVisibility(View.VISIBLE);
			mFooterWccImageView.clearAnimation();
			mFooterWccImageView.startAnimation(mFlipAnimation);
			mFooterTextView.setText("松开即可获取更多");
			break;
		case PULL_TO_REFRESH:
			mFooterProgressBar.setVisibility(View.GONE);
			mFooterTextView.setVisibility(View.VISIBLE);
			mFooterUpdateTextView.setVisibility(View.VISIBLE);
			mFooterWccImageView.clearAnimation();
			mFooterWccImageView.setVisibility(View.VISIBLE);
			// 是由RELEASE_To_REFRESH状态转变来的
			if (isBack) {
				isBack = false;
				mFooterWccImageView.clearAnimation();
				mFooterWccImageView.startAnimation(mReverseFlipAnimation);
			}
			 
			mFooterTextView.setText("上拉可以获取更多");
			break;
		case LOADMORE_FAILURE:
			mFooterWccImageView.setVisibility(View.GONE);
			 mFooterProgressBar.setVisibility(View.GONE);
			 mFooterTextView.setVisibility(View.VISIBLE);
			 mFooterUpdateTextView.setVisibility(View.GONE);
			 mFooterTextView.setText("加载失败,点击重试");
			 setFooterBottomHeight(mFooterViewHeight);
			break;	
		case REFRESHING:
			boolean needRefreshing = more();
			if(needRefreshing) {
				pageNum++;
				if (footMode == FootViewMode.ClickAble)
				{			
					mFooterWccImageView.setVisibility(View.GONE);
					mFooterProgressBar.setVisibility(View.VISIBLE);
					mFooterTextView.setVisibility(View.VISIBLE);
					mFooterUpdateTextView.setVisibility(View.GONE);
					mFooterTextView.setText("更多内容加载中...");
					setFooterBottomHeight(mFooterViewHeight);
				}
			}
			break;
		case DONE:  
			mFooterProgressBar.setVisibility(View.GONE);
			mFooterWccImageView.clearAnimation();
			mFooterWccImageView.setImageResource(R.mipmap.ic_pulltorefresh_arrow);
			mFooterUpdateTextView.setVisibility(View.VISIBLE);
			mFooterTextView.setText("上拉可以获取更多");
			setFooterBottomHeight(0);
			break;
		}
	}

	/**
	 * 是否应该到了父View,即PullToRefreshView滑动
	 * 
	 * @param deltaY , deltaY > 0 是向下运动(sub view滑到了顶端), < 0是向上运动（sub view滑到底部)
	 * @return
	 */
	private boolean isRefreshViewScroll(int deltaY) {
		if (mHeaderState == REFRESHING || mFooterState == REFRESHING) {
			return false;
		}
 
		// 对于ListView和GridView
		if (mAdapterView != null) {
			// 子view(ListView or GridView)滑动到最顶端
			if (deltaY > 0 && Math.abs(deltaY) > 10) {

				View child = mAdapterView.getChildAt(0);
				if (child == null) {
					// 如果mAdapterView中没有数据,不拦截
					
					return true;
				}
				if (mAdapterView.getFirstVisiblePosition() == 0
						&& child.getTop() == 0) {
					
					return true;
				}
				int top = child.getTop();
				int padding = mAdapterView.getPaddingTop();
				if (mAdapterView.getFirstVisiblePosition() == 0
						&& Math.abs(top - padding) <= 8) {// 这里之前用3可以判断,但现在不行,还没找到原因
					
					return true;
				}

			} else if (deltaY < 0 && Math.abs(deltaY) > 10) {
				View lastChild = mAdapterView.getChildAt(mAdapterView.getChildCount() - 1);
				if (lastChild == null) {
					// 如果mAdapterView中没有数据,不拦截
					return false;
				}
				// 最后一个子view的Bottom小于父View的高度说明mAdapterView的数据没有填满父view,
				// 等于父View的高度说明mAdapterView已经滑动到最后
				if (lastChild.getBottom() <= getHeight()
						&& mAdapterView.getLastVisiblePosition() == mAdapterView.getCount() - 1) {
					
					return true;
				}
			} else
				return false;
		}
		// 对于ScrollView
		if (mScrollView != null) {
			// 子scroll view滑动到最顶端
			View child = mScrollView.getChildAt(0);
			if (deltaY > 0 && mScrollView.getScrollY() == 0) {
				
				return true;
			} else if (deltaY < 0
					&& child.getMeasuredHeight() <= getHeight()
							+ mScrollView.getScrollY()) {
				
				return true;
			}
		}
		return false;
	}

	/**
	 * 设置header view 的topMargin的值
	 * @param topMargin  为0时，说明header view 刚好完全显示出来； 为-mHeaderViewHeight时，说明完全隐藏了
	 *           
	 */
	private void setHeaderTopMargin(int topMargin) {
		LayoutParams params = (LayoutParams) mHeaderView.getLayoutParams();
		params.topMargin = topMargin;
		mHeaderView.setLayoutParams(params);
		invalidate();
	}
	
	/**
	 * 设置footer view 的height值
	 *为0时，说明footer view GONE； 为mFootViewHeight时，说明完全显示了
	 *           
	 */
	private void setFooterBottomHeight(int bottomHeight) {
		LayoutParams params = (LayoutParams) mFooterView.getLayoutParams();
		params.height = bottomHeight;
		mFooterView.setLayoutParams(params);
		if(bottomHeight > 0)
			mFooterView.setVisibility(View.VISIBLE);
		else 
			mFooterView.setVisibility(View.GONE);
		mFooterView.invalidate();
	}

	/**
	 * header view 完成更新后恢复初始状态
	 * 
	 */
	public void onHeaderRefreshComplete() {
 		mHeaderState = PULL_TO_REFRESH;
		state = DONE;
		mHeaderUpdateTextView.setText("最近更新:" + new Date(System.currentTimeMillis()).toLocaleString());
		changeHeaderViewByState(); 
	}

	 

	/**
	 * footer view 完成更新后恢复初始状态
	 */
	public void onFooterRefreshComplete() {
 		mFooterState = PULL_TO_REFRESH;
		state = DONE;
		mFooterUpdateTextView.setText("最近更新:" + new Date(System.currentTimeMillis()).toLocaleString());
		changeFooterViewByState();
	}
 	
	/**
	 * should be called after setData(list,pageNum,pageSize) 
	 * @param FailLoadMore
	 */
	public void onComplete(boolean FailLoadMore) {
		state = DONE;
		
		changeHeaderViewByState(); 
		
		mFooterUpdateTextView.setText("最近更新:" + new Date(System.currentTimeMillis()).toLocaleString());
	 
		if( footMode == FootViewMode.ClickAble && FailLoadMore)
			state = LOADMORE_FAILURE;	
		else if (FailLoadMore) {
			Toast.makeText(getContext(), "网络服务异常!", Toast.LENGTH_SHORT).show();
		}
		changeFooterViewByState();
		
		if (mList != null) { // for static page list content change			 
			lastPos = mList.getLastVisiblePos();
		} else
			lastPos = 0;	 
		scrollToPosition(lastPos);

	}
	
	/**
	 * Set a text to represent when the list was last updated.
	 * 
	 * @param lastUpdated
	 *            Last updated at.
	 */
	public void setLastUpdated(CharSequence lastUpdated) {
		if (lastUpdated != null) {
			mHeaderUpdateTextView.setVisibility(View.VISIBLE);
			mHeaderUpdateTextView.setText(lastUpdated);
		} else {
			mHeaderUpdateTextView.setVisibility(View.GONE);
		}
	}

	/**
	 * Interface definition for a callback to be invoked when list/grid footer
	 * view should be refreshed.
	 */
	public interface OnFooterRefreshListener {
		public void onFooterRefresh(PullToRefreshView view);
	}

	/**
	 * Interface definition for a callback to be invoked when list/grid header
	 * view should be refreshed.
	 */
	public interface OnHeaderRefreshListener {
		public void onHeaderRefresh(PullToRefreshView view);
	}

	public interface OnRefreshListener {
		public void onRefresh();

		public void onGetPageData();
		
		/**
		 * 上拉加载更多回调方法，v8.4增加了boolean类型的返回值，为了在Activity中控制分页显示，当page<pages,返回true;当page>=pages,返回false
		 * @param nextPageNum
		 * @return false-不需要加载更多;true-需要加载更多
		 */
		public boolean onMore(int nextPageNum);

		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
							 int totalItemCount);
	}

	public void setOnRefreshListener(OnRefreshListener refreshListener) {
		this.refreshListener = refreshListener;
	}

	private void refresh() {
		which = THIS_PAGE;
		isRecored = false;
		lastPos = 0;
		if (refreshListener != null) {
			refreshListener.onRefresh();
		}
	}



	private boolean more() {
		which = THIS_PAGE;
		isRecored = false;
		lastPos = DATA_SIZE;
 	 
		if (refreshListener != null)  {		
			if(mList != null)
				return refreshListener.onMore(mList.getNextRemotePageNum());
			else
				return refreshListener.onMore(1);
		}
		return false;
	}
	
	public void scrollToPosition(int anItemPos) {
		if (anItemPos != AdapterView.INVALID_POSITION) {
			if(mAdapterView instanceof GridView) {
				GridView gridview = (GridView) mAdapterView;
				if(anItemPos != 0)
					anItemPos += 2; //for grid
				if(Build.VERSION.SDK_INT >= 8) {					
					gridview.smoothScrollToPosition(anItemPos);
				} else {
					gridview.setSelection(anItemPos);
					gridview.clearFocus();
				}	 
			} else if(mAdapterView instanceof ListView) {
				ListView listview = (ListView) mAdapterView;
				listview.setSelection(anItemPos);
				listview.clearFocus();
			}
		}
	}
}